# Creatyour views here.
from django.template import Context, loader
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.syndication.feeds import Feed

from monkeystudio.blogs.views import *
from monkeystudio.blogs.models import Post, Comment

from datetime import datetime

from akismet import *
import os


api_key = "5d1f85e18f33"

def akismeterror( request, post_id):
  return render_to_response('post_error.html', {'post_id' : post_id})

def comment( request, post_id ):
  author = request.POST['author']
  email  = ''#request.POST['email']
  url    = ''#request.POST['url']
  #remote = os.environ["REMOTE_ADDR"]
  remote = request.META['REMOTE_ADDR']
  #agent  = os.environ["HTTP_USER_AGENT"]
  agent  = request.META['HTTP_USER_AGENT']

  data = {'user_ip' : remote, \
          'user_agent' : agent, \
          'comment_author' : author, \
          'comment_author_email' : email,  \
          'comment_author_url' : url }
  message = request.POST['message']
  
  p = get_object_or_404(Post, pk=post_id)
  
  if author  == '':
    author = 'Anonymous'
  posturl = 'http://monkeystudio.org/blog/'

  api = Akismet(api_key, posturl, agent="Monkey Blog/0.1" )
  try:
    if api.verify_key():
      if api.comment_check(message, data):
        HttpResponse("Spam");
      else:
        c = Comment()
        c.post_id = post_id
        c.author = author
        c.text = message
        c.email = email
        c.url = url
        c.save()
  except AkismetError:
    return HttpResponseRedirect('/news/%s/akismeterror/' % post_id)
    
  return HttpResponseRedirect('/news/%s/' % post_id)

class LatestNews (Feed):
  title = "Monkeystudio Qt4 IDE News Feed"
  link  = "/news/"
  description = "Updates and Changes in Monkeystudio Development"

  def items (self):
    return Post.objects.order_by('-pub_date')

  def item_pubdate (self, item):
    return item.pub_date
   
